<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 工人报工管理
 */
class WorkerReport extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\Report;
    }

    /**
     * 工人报工列表
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['allocation.process', 'allocation.user', 'allocation.order'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id', 'allocation_id', 'reported_quantity', 'actual_hours', 'quality_status', 'remark', 'createtime', 'audit_status']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 工人报工页面
     */
    public function report($allocation_id = null)
    {
        if (!$allocation_id) {
            $this->error('参数错误');
        }
        
        // 获取分工分配信息
        $allocation = \app\admin\model\scanwork\Allocation::with(['process', 'order', 'model.product'])
            ->where('id', $allocation_id)
            ->find();
            
        if (!$allocation) {
            $this->error('分工分配不存在');
        }
        
        $this->view->assign('allocation', $allocation);
        return $this->view->fetch();
    }

    /**
     * 保存工人报工
     */
    public function saveReport()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            
            $allocationId = $params['allocation_id'];
            $reportedQuantity = (int)$params['reported_quantity'];
            $actualHours = (float)$params['actual_hours'];
            $qualityStatus = (int)$params['quality_status'];
            $remark = $params['remark'];
            
            // 获取分工分配信息
            $allocation = \app\admin\model\scanwork\Allocation::get($allocationId);
            if (!$allocation) {
                $this->error('分工分配不存在');
            }
            
            // 检查报工数量是否超过分配数量
            $totalReported = \app\admin\model\scanwork\Report::where('allocation_id', $allocationId)
                ->sum('reported_quantity');
            $remainingQuantity = $allocation->quantity - $totalReported;
            
            if ($reportedQuantity > $remainingQuantity) {
                $this->error('报工数量不能超过剩余分配数量（剩余：' . $remainingQuantity . '）');
            }
            
            Db::startTrans();
            try {
                // 创建报工记录
                $reportData = [
                    'allocation_id' => $allocationId,
                    'reported_quantity' => $reportedQuantity,
                    'actual_hours' => $actualHours,
                    'quality_status' => $qualityStatus,
                    'remark' => $remark,
                    'audit_status' => 0, // 待审核
                    'createtime' => time(),
                    'updatetime' => time()
                ];
                
                $report = \app\admin\model\scanwork\Report::create($reportData);
                
                // 更新分工分配状态
                $allocation->reported_quantity = $totalReported + $reportedQuantity;
                if ($allocation->reported_quantity >= $allocation->quantity) {
                    $allocation->status = 2; // 已完成
                } else {
                    $allocation->status = 1; // 进行中
                }
                $allocation->save();
                
                Db::commit();
                $this->success('报工提交成功，等待审核');
            } catch (Exception $e) {
                Db::rollback();
                $this->error('报工提交失败：' . $e->getMessage());
            }
        }
        $this->error('参数错误');
    }

    /**
     * 审核报工
     */
    public function audit()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            
            $reportId = $params['report_id'];
            $auditStatus = (int)$params['audit_status'];
            $auditRemark = $params['audit_remark'];
            
            $report = \app\admin\model\scanwork\Report::get($reportId);
            if (!$report) {
                $this->error('报工记录不存在');
            }
            
            Db::startTrans();
            try {
                // 更新报工记录
                $report->audit_status = $auditStatus;
                $report->audit_remark = $auditRemark;
                $report->audit_time = time();
                $report->save();
                
                // 如果审核通过，更新分工分配
                if ($auditStatus == 1) {
                    $allocation = $report->allocation;
                    $allocation->actual_hours += $report->actual_hours;
                    $allocation->save();
                }
                
                Db::commit();
                $this->success('审核完成');
            } catch (Exception $e) {
                Db::rollback();
                $this->error('审核失败：' . $e->getMessage());
            }
        }
        $this->error('参数错误');
    }
}
